﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

///<summary>
///
///</summary>
public class EnemyComponent : MonoBehaviour
{
    //public GameObject balloon;
    public GameObject Enemy;
    Animator EnemyAni;
    public GameObject endLight;
    public GameObject Break;
    public GameObject debris;
    GameObject Win;
	float gravityScale;
	//触碰闪电
	//地面
	GameObject floor;
	bool IsPlaySound = false;

    bool IsDie = false;
    // Start is called before the first frame update
    private void Awake()
    {
        DontDestroyOnLoad(gameObject);
        Debug.Log("加入不可销毁" + gameObject.name);
    }
    void Start()
    {
		floor = GameObject.Find("Canvas/GameView/BackGround/floor");
        EnemyAni = Enemy.GetComponent<Animator>();
    }
    public void OnEnable()
    {
        IsDie = false;
		IsPlaySound = false;
		debris.SetActive(false);
        Enemy.SetActive(true);
        Break.SetActive(false);
        endLight.SetActive(false);
            Win = GameObject.Find("Canvas/GameView/BackGround/triggerWin");
		SpeedUp(GameConfig.SpeedState);
	}
    private void Update()
    {
        if (IsDie)
            return;
        SpeedUp(GameConfig.SpeedState);

        if (GetComponentsInChildren<BalloonInputKeyComponent>().Length < 1)
		{
            PlayerComponent.Instance.MoveingToEnemyPosX(transform.position);
            gravityScale = 100f;
			GetComponent<Rigidbody2D>().gravityScale = gravityScale;
			EnemyAni.SetBool("IsBreak", true);
			if(!IsPlaySound)
			SoundPath();
            IsDie = true;
		}
	}
	public void SoundPath()
	{
		IsPlaySound = true;
		int num = UnityEngine.Random.Range(0, 3);
		if (gameObject.name.Equals("Enemy1(Clone)"))
		{
			PlaySound("Sounds/Enemy/knight_surprise" + num);
		}
		else if (gameObject.name.Equals("Enemy2(Clone)"))
		{
			PlaySound("Sounds/Enemy/dark_knight0");
		}
		else if(gameObject.name.Equals("Enemy3(Clone)"))
		{
			PlaySound("Sounds/Enemy/golden_knight_grunt1");
		}
	}


	void PlaySound(string path)
	{
		AudioManager.GetInstance.Play(path);
	}
	public void ClearBalloonOneType()
	{
		BalloonType randomNum = 0;
		List<BalloonType> balloonTypeList = new List<BalloonType>();
		BalloonInputKeyComponent[] balloonInputKeys = GetComponentsInChildren<BalloonInputKeyComponent>();
		if (balloonInputKeys.Length> 0)
		{
			for(int i = 0; i < balloonInputKeys.Length; i++)
			{
				balloonTypeList.Add(balloonInputKeys[i].GetBalloonType());
			}
			randomNum = balloonTypeList[UnityEngine.Random.Range(0, balloonTypeList.Count)];
			for (int i = 0; i < balloonInputKeys.Length; i++)
			{
				if (balloonInputKeys[i].GetBalloonType() == randomNum)
				{
					balloonInputKeys[i].Break();
					return;
				}
			}
		}
	}


    public void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.collider.tag == "floor")
        {
           if (GetComponentsInChildren<BalloonInputKeyComponent>().Length < 1)
           {
                AppFacde.Instance.SendNotification(GameEvents.ADD,4);
                GoldManager.Instance.EnemyGoldExpolde(transform.position, 4, transform);
                debris.SetActive(true);
                Break.SetActive(true);
                Enemy.SetActive(false);
                if (Win.GetComponent<GroundEnemyWin>().IsOpen)
                   Win.GetComponent<GroundEnemyWin>().ReturnInitPos();
           }
           else
           {
               if (!GameConfig.IsGameOver)
               {
                   Debug.Log("游戏失败");
					PlaySound("Sounds/gameOver/knight_cheer");
				   SendNotification(GameEvents.GAME_OVER);
                   EnemyAni.SetBool("IsEnemyWin", true);
                   GameConfig.IsGameOver = true;
                   endLight.SetActive(true);
               }
               else
               {
                   EnemyAni.SetBool("IsEnemyWin", true);
               }
           }
        }
		if (collision.collider.tag == "die")
		{
            AppFacde.Instance.SendNotification(GameEvents.ADD, 4);
            GoldManager.Instance.EnemyGoldExpolde(transform.position, 4, transform);
            debris.SetActive(true);
            Break.SetActive(true);
            Enemy.SetActive(false);
			if (Win.GetComponent<GroundEnemyWin>().IsOpen)
				Win.GetComponent<GroundEnemyWin>().ReturnInitPos();
		}
		
    }
    private void OnCollisionStay2D(Collision2D collision)
    {
        if (collision.collider.tag == "floor")
        {
           if (GetComponentsInChildren<BalloonInputKeyComponent>().Length < 1)
           {
              if(Break.GetComponent<ImageSpriteChageComponet>().aniFinish)
               {

                    Break.SetActive(false);
                    CoinComponent[] coins = GetComponentsInChildren<CoinComponent>();
                    if (coins.Length == 0)
                    {
                        gameObject.SetActive(false);
                    }
                    else
                    {
                        for(int i = 0; i < coins.Length; i++)
                        {
                            coins[i].Recycle();
                        }
                        gameObject.SetActive(false);
                    }

               }
           }
        }
        else if(collision.collider.tag=="die")
        {
			if (Break.GetComponent<ImageSpriteChageComponet>().aniFinish)
			{
				Break.SetActive(false);
                CoinComponent[] coins = GetComponentsInChildren<CoinComponent>();
                if (coins.Length == 0)
                {
                    gameObject.SetActive(false);
                }
                else
                {
                    for (int i = 0; i < coins.Length; i++)
                    {
                        coins[i].Recycle();
                    }
                    gameObject.SetActive(false);
                }
			}
		}
		else
		{
			return;
		}
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "trigger")
        {
            if (!GameConfig.IsGameOver)
            {
                if (GetComponentsInChildren<BalloonInputKeyComponent>().Length >=1)
                {
                    Win.GetComponent<GroundEnemyWin>().End();
                }
            }
        }
		else if (collision.tag == "Lightning")
		{
			if (transform.name != "Enemy1(Clone)")
				return;
			BalloonBreak();
			GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeAll;
			EnemyAni.SetBool("IsLightning", true);
		}
	}
    void SendNotification(string notification)
    {
        AppFacde.Instance.SendNotification(notification);
    }

    public void SpeedUp(bool stateFinish)
	{
		if (stateFinish)
		{
			gravityScale = 100f;
			GetComponent<Rigidbody2D>().gravityScale = gravityScale;
			BalloonBreak();
		}
		else if(!stateFinish)
		{
			gravityScale = 5f;
			GetComponent<Rigidbody2D>().gravityScale = gravityScale;
		}
	}
	
	public float ObjAndFloorDistance()
	{
		float floor_y = floor.transform.position.y;
		float obj_y = transform.position.y;
		return Mathf.Abs(floor_y - obj_y);
	}

	public void BalloonBreak()
	{
		GetComponent<BalloonSubject>().BalloonBreak();
		GetComponent<Rigidbody2D>().gravityScale = 100f;
	}
	public void EnemyRecycle()
	{
        transform.SetParent(GameObject.Find("EnemyFactory").transform);
        gameObject.SetActive(false);
		endLight.SetActive(false);
	}   

    private void OnDestroy()
    {
        Debug.Log("被销毁" + "怪物名：" + gameObject.name);
    }
}
